// pages/login/index.js
import { Base64 } from '../../utils/base64';
import {getTagData, long2Bytes, randomStr, randonNum, Uint8Array2HexStr} from '../../utils/util';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        formData: {
          
        },
        rules: [{
                name: 'loginName',
                rules: {required: true, message: '请输入账号'},
            }, {
                name: 'loginPwd',
                rules: {required: true, message: '请输入密码'},
            },{
                name: 'captcha',
                rules: {required: true, message: '请输入验证码'},
            }
        ]
    },

    tapEyes: function() {
        this.setData({showPwd: !this.data.showPwd});
    },

    formInputChange(e) {
        const {field} = getTagData(e)
        this.setData({
            [`formData.${field}`]: e.detail.value
        })
    },

    submitForm() {
        this.selectComponent('#form').validate((valid, errors) => {
            console.log('valid', valid, errors)
            if (!valid) {
                const firstError = Object.keys(errors)
                if (firstError.length) {
                    wx.showToast({
                      title: errors[firstError[0]].message,
                      icon: 'none'
                    })
                }
            } else {
              const payload = {...this.data.formData};
              const arrayPwd = Array.from(randonNum(3) + payload.loginPwd, char => char.charCodeAt(0));
              console.log(arrayPwd)
              if(arrayPwd.some(a => a > 0xFF)) {
                wx.showToast({
                  title: '不支持特殊密码',//123122@ MTIzMTIyQA==
                  icon: 'none'
                })
                return;
              }
              payload.loginPwd = Base64.base64EncArr(arrayPwd);
               wx.$http.post({url: '/szm/login', data: payload, noToken: true}).then(res => {
                    const {token, expire, userId, parentId, keeloqkey} = res.data
                    wx.setStorageSync('szm_token', {token, expire: Date.now() + parseInt(expire), userId, parentId, keeloqkey})
                    const pages = getCurrentPages();
                    if(pages && pages.length > 1) {
                        wx.navigateBack()
                    } else {
                        wx.reLaunch({
                          url: '/pages/index/index',
                        })
                    }
               }).catch(err => {
                  this.getCaptcha(false);
               })
            }
        })
    },

    tapCaptcha: function() {
        this.getCaptcha();
    },

    tapForgot: function (params) {
        wx.navigateTo({
          url: '/pages/mine/pwd/pwd?forgot=1',
        })  
    },
    tapEnroll: function (params) {
        wx.navigateTo({
          url: '../enroll/enroll',
        })  
    },
    bingAutoLogin: function(e) {
      console.log(e.detail.value)
      this.setData({
        [`formData.autoLogin`]: e.detail.value?.length > 0 ? 1 : 0
      })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      const {openid, unionid} = wx.getStorageSync('wechatInfo');
      const {formData} = this.data;
      Object.assign(formData, {openid, unionid, autoLogin: 1});
      this.setData({formData});
        wx.hideTabBar();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getCaptcha();
        const {promise, state} = wx.$wechatLogin;
        if(state === "pending") {
          promise.then(({tokenMap}) => {
            if(tokenMap) {
              wx.reLaunch({
                url: '/pages/index/index',
              })
            }
          });
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        wx.showTabBar();
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    getCaptcha(showLoading) {
        const uuid = randomStr();
        this.setData({
            [`formData.uuid`]: uuid
        })
        wx.$http.get({url: '/szm/captcha', data: {uuid, bgc: '#f1f1f1'}, responseType: 'arraybuffer', showLoading, noToken: true}).then(res => {
            console.log(res)
            this.setData({captchaSrc: res})
        })
    },
    tapNoLogon: function (params) {
        wx.navigateBack()
    }
})